<template>
	<div class="detail-container point-detail-container">
    <detail-header :detailAll="{'detail':detailAll}"></detail-header>
    <div class="detail-con">
      <div class="item-block address" v-if="detailAll.self_address_id>0 && detailAll.shipping_type==4">
        <div class="left"></div>
        <div class="right">
          <div class="name">【自提地址】</div>
          <div class="addr">{{detailAll.self_take_address}}</div>
        </div>
      </div>

      <div class="item-block address" v-else>
        <div class="left"></div>
        <div class="right">
          <div class="name">{{detailAll.name}} {{detailAll.mobile}}</div>
          <div class="addr">{{detailAll.province_id}}{{detailAll.city_id}}{{detailAll.area_id}}{{detailAll.town_id}}{{detailAll.address}}</div>
        </div>
      </div>
      
      <!-- 商品信息 -->
      <point-goods-info :detailAll="detailAll"></point-goods-info>

      <!-- 运费总积分等信息 -->
      <div class="item-block">
        <div class="price-con">
          <div class="label">运费</div>
          <div class="line-detail" v-if="detailAll.freight_payer==4">到付</div>
          <div class="line-detail" v-else>
            <span>&yen;{{detailAll.post_fee || '0.00'}}</span>
          </div>
        </div>
        <div class="total-price">
          <span>兑换{{detailAll.point_name}}：</span>
          <span class="price">{{detailAll.points}}</span>
        </div>
      </div>

      <div
        class="item-block item-block2"
        v-if="detailAll.message"
      >
        <div class="title">订单信息</div>
        <div class="line-con" v-if="detailAll.message">
          <div class="label">买家留言：</div>
          <div class="line-detail">{{detailAll.message}}</div>
        </div>
      </div>

      <div>
        <!-- 运单信息 -->
        <express-info
          v-if="detailAll.address_id != 0 && (detailAll.status == 1 || detailAll.status == 2 || detailAll.status == 3) && detailAll.dis_order_lists[0].express_no"
          :detail="detailAll"
        ></express-info>
      </div>
      <order-log-info :order_verify_log="order_verify_log" />
      <!-- 自提二维码 -->
      <order-code :detailAll="detailAll"></order-code>

      <div class="actions" v-if="detailAll.status==2 || detailAll.status==0 || (detailAll.status==1 && detailAll.is_allow_return)">
        <div class="bottom-btn">
          <van-button round hairline class="btn no-border" v-if="detailAll.status==2" @click="clickConfirm(detailAll.point_exchange_order_id)">确认收货</van-button>
          <van-button round hairline class="btn no-border" v-else-if="detailAll.status==0" @click="clickPay(detailAll)">付款</van-button>
          <van-button round hairline class="btn no-border return-btn" v-else-if="detailAll.status==1 && detailAll.is_allow_return" @click="JumpName('pointOrderRefunding',{id:detailAll.point_exchange_order_id})">退款</van-button>
          <!-- 等待买家自提 可以退款 可以和收货按钮共存 -->
          <van-button round hairline class="btn no-border return-btn refund-btn-top" v-if="detailAll.status==2 && detailAll.is_allow_return && detailAll.is_self_take == 1" @click="JumpName('pointOrderRefunding',{id:detailAll.point_exchange_order_id})">退款</van-button>
        </div>
      </div>
    </div>

    <!-- 付款弹窗 -->
    <van-popup v-model="showPayPop" class="pay-box" position="top" :style="{ height: '100%' }">
      <!-- <tx-pop @closePop="closeCashPop" :dzData="dzData" :cashPopData="cashPopData"></tx-pop> -->
      <more-payment @closePayPop="closePayPop" :isTlfzPay="isTlfzPay" :isHffzPay="true" @payCallback="payCallback" :payPopData="payPopData"></more-payment>
    </van-popup>  
  </div>
</template>

<script>
  import { pointExchangeOrderDetail, pointPayUrl, pointOrderConfirm } from '@/api/user/member/memberApi.js'
  import pointGoodsInfo from './components/pointGoodsInfo'
  import orderCode from './components/orderCode'
  import MorePayment from '@/components/MorePayment/index'
  import PayPassword from '@/components/PayPassword/index'
  import small from '@/smallapp/small'
  import {
    detailHeader,
    expressInfo,
    orderLogInfo
  } from './../../../order/detail/components/'
  import Vue from 'vue'
  export default Vue.extend({
    name: 'index',
    components: {
      MorePayment,
      PayPassword,
      detailHeader,
      pointGoodsInfo,
      expressInfo,
      orderCode,
      orderLogInfo
    },
    data() {
      return {
        order_verify_log: [],
        detailAll: {},
        must_pay_password: false, // 强制设置支付密码
        popup_show: '',
        showPayPop: false, // 付款弹窗
        showPwd: false, // 支付密码弹框是否显示
        is_alipay: null,
        is_wx_pay: null,
        is_cod: null,
        is_bank: null,
        is_paypal: null,
        is_beibao: null,
        is_offline: null,
        is_hantePay: null,
        payPopData: {

        },
        submitData: {},
        isTlfzPay: false,
        remark: false
      }
    },
    watch: {
      $route: {
        handler(val, oldVal) {
          if (val.query.express_no != oldVal.query.express_no) {
            this.init()
          }
        },
        // 深度观察监听
        deep: true
      }
    },
    methods: {
      init() {
        const params = {
          id: this.$route.query.id
        }
        if (this.$route.query.express_no) {
          params.express_no = this.$route.query.express_no
        }

        this.$loadingWrap.show()
        setTimeout(() => {
          this.$loadingWrap.close()
        }, 10000)
  
        pointExchangeOrderDetail(params).then(res => {
          this.$loadingWrap.close()
          if (res.status == 1) {
            const resData=res.data
            this.detailAll = resData
            this.order_verify_log = res.data.order_verify_log || []
            const pageTitle = (this.detailAll.point_name || '积分') + '兑换商品订单详情'
              wx.setNavigationBarTitle({
                title: pageTitle
              })
            // 付款弹窗信息
            this.payPopData.balance = resData.balance
            this.payPopData.is_dhs_allow_deposit = resData.is_dhs_allow_deposit
            this.payPopData.is_check_dhs = resData.is_check_dhs
            this.payPopData.dhs_deposit = resData.dhs_deposit
            this.payPopData.deposit_alias = resData.deposit_alias
            this.payPopData.default_pay_type = resData.default_pay_type // 默认付款方式
            this.payPopData.default_pay = resData.default_pay // hantePay默认付款方式
            this.payPopData.is_open_balance_pay = resData.is_open_balance_pay // 是否开启余额支付
          } else {
            this.$Error(res.msg)
          }
        })
      },
      // 确认收货
      clickConfirm(id) {
        pointOrderConfirm({ id: id }).then(res => {
          if (res.status == 1) {
            this.$Error('操作成功')
            this.init()
          } else {
            this.$Error(res.msg)
          }
        })
      },
  
      // 点击付款
      clickPay(item) {
      // if (!is_alipay && !is_wx_pay && !is_cod && !is_bank && !is_paypal && !is_beibao && !is_offline && !is_hantePay) {
      /* if (!(this.is_alipay == 1 || this.is_wx_pay == 1 || this.is_cod == 1 || this.is_bank == 1 || this.is_paypal == 1 || this.is_beibao == 1 || this.is_offline == 1 || this.is_han_te_pay == 1)) {
        this.$Error('抱歉，暂时不能付款！')
        return false
      } */
      /* const payType = item.pay_type
      const peerType = item.peer_type
      // 全部订单列表代码
      if (payType == 5) {
        window.location.href = '/Paypal/doPaypal/order_id/' + item.point_exchange_order_id
        return false
      } else if (payType == 7 && peerType == 2) {
        window.location.href = '/PeerPay/peer_detail/id/' + item.point_exchange_order_id
        return false
      } */
        this.payPopData.payment = item.post_fee
        this.payPopData.order_id = item.point_exchange_order_id
        this.payPopData.is_open_balance_pay = item.is_open_balance_pay
        this.payPopData.isKuajing = item.isKuajing
        this.payPopData.tlfz_point_exchange = item.tlfz_point_exchange == 1
        this.isTlfzPay = item.tlfz_point_exchange == 1
        this.showPayPop = true
      },

      // 关闭付款弹窗
      closePayPop() {
        this.showPayPop = false
      },
      Jump(url, data) {
        this.$JumpPath(this, url, data)
      },
      // 点击确定付款，付款请求
      payCallback(submitData) {
        // console.log(submitData)
        this.submitData = submitData
        // var payType = $('input[name="type"]:checked').val()
        const payType = submitData.type
        const order_id = submitData.order_id
        const money_type = submitData.moneyType
        // var money_type = $('input[name="money_type"]:checked').val()
        const popup_show = this.popup_show
        // var popup_show = $('#popup_show').val()
        // const balance = this.payPopData.balance
        const payment = this.payPopData.payment
        // var sumPrice = $('.balance_money').text()
        // const must_pay_password = this.must_pay_password
        // var must_pay_password = $(':hidden[name="must_pay_password"]').val()
        const global_alipay_currency = submitData.global_alipay_currency
        // var global_alipay_currency = $('[name=global_alipay_currency]').val()
        // // console.log(must_pay_password);
        const hantepay = submitData.hantepay
        // var hantepay = $('[name=hantepay]:checked').val()// 定制HantePay
        if (payType == 34) {
          params.adapay_pay_type = submitData.adapay_pay_type
        }
        // 是否强制使用支付密码
        if (this.must_pay_password == 1) {
          if (money_type == 2 && payment > 0) {
            this.$Error('请先去会员中心的修改资料里设置支付密码!')
          } else {
            const params = { hantepay: hantepay, global_alipay_currency: global_alipay_currency, pay_type: payType, order_id: order_id, money_type: money_type }
            this.$loadingWrap.show()
            setTimeout(() => {
              this.$loadingWrap.close()
            }, 10000)
            pointPayUrl(params).then(res => {
              this.$loadingWrap.close()
              if (res.status == 1) {
                // window.location.href = res.url
                // TODO 小程序支付
                if(this.submitData.type == 2 && res.data.jsApiParameters){
                  const payData = JSON.parse(res.data.jsApiParameters)
                  wx.requestPayment({
                    timeStamp: payData.timeStamp,
                    nonceStr: payData.nonceStr, //
                    package: payData.package, //
                    signType: payData.signType, //微信签名方式
                    paySign: payData.paySign, //微信签名
                    success: (res) => {
                      // console.log(res)
                      this.getPointOrder(this.curType)
                      this.closePayPop()
                    },
                    fail: (failmsg) => {
                      // console.log(failmsg)
                    }
                  })
                } else if (this.submitData.type == 26 && res.data.is_mini_vsp) {
                  this.Jump('/buyTonglianWait',{ order_id, pay_type: 3 })
                } else if (this.submitData.type == 34 && res.data.jsApiParameters) {
                  if (small.wxCache('adapayPlugVersion') == 'jump_adapay_mini') {
                    const jsApiParameters = typeof res.data.jsApiParameters === 'object' ? res.data.jsApiParameters : JSON.parse(res.data.jsApiParameters) 
                    this.hfAppId = jsApiParameters.wx_app_id
                    const that = this
                    wx.navigateToMiniProgram({
                      appId: jsApiParameters.wx_app_id,
                      path: jsApiParameters.miniapp_path,
                      success(res) {
                        // 打开成功
                        // console.log(res)
                      },
                      fail(error) {
                        // that.$Error('跳转失败')
                        that.Jump('pointOrder')
                      }
                    })
                  } else if (small.wxCache('adapayPlugVersion') == 'self') {
                    const payData = JSON.parse(res.data.jsApiParameters)
                    wx.requestPayment({
                      timeStamp: payData.timeStamp,
                      nonceStr: payData.nonceStr, //
                      package: payData.package, //
                      signType: payData.signType, //微信签名方式
                      paySign: payData.paySign, //微信签名
                      success: (res) => {
                        // console.log(res)
                        this.getPointOrder(this.curType)
                        this.closePayPop()
                      },
                      fail: (failmsg) => {
                        // console.log(failmsg)
                      }
                    })
                  } else {
                    const adapayPlugin = small.wxCache('adapayPlugVersion') == 'new' ? requirePlugin("Adapay") : requirePlugin("adapay-plugin")              
                    // 汇付分账
                    this.isSubmit = false
                    // console.log('typeof obj',  typeof res.data.jsApiParameters === 'object')
                    const hfPay= res.data.jsApiParameters
                    if (hfPay) {
                      adapayPlugin.requestPay(hfPay, this.paySuccess, this.payError);
                    }
                  }
                } else{
                  setTimeout(() => {
                    this.init()
                  }, 1000)
                  this.closePayPop()
                }
                /* if (money_type == 2) {
                  setTimeout(() => {
                    this.init()
                  }, 1000)
                  this.closePayPop()
                  
                } else {
                  smallpay.wxOrderPay(res.data.jsApiParameters)
                } */
              } else {
                this.$Error(res.msg)
              }
            })
          }
        } else {
          if (money_type == 2 && popup_show) {
            this.showPwd = true
          } else {
            const params = { hantepay: hantepay, global_alipay_currency: global_alipay_currency, pay_type: payType, order_id: order_id, money_type: money_type }
            if (payType == 34) {
              params.adapay_pay_type = submitData.adapay_pay_type
            }
            this.$loadingWrap.show()
            setTimeout(() => {
              this.$loadingWrap.close()
            }, 10000)
            pointPayUrl(params).then(res => {
              this.$loadingWrap.close()
              if (res.status == 1) {
                // window.location.href = res.url
                // TODO 小程序支付
                if(this.submitData.type == 2 && res.data.jsApiParameters){
                  const payData = JSON.parse(res.data.jsApiParameters)
                  wx.requestPayment({
                    timeStamp: payData.timeStamp,
                    nonceStr: payData.nonceStr, //
                    package: payData.package, //
                    signType: payData.signType, //微信签名方式
                    paySign: payData.paySign, //微信签名
                    success: (res) => {
                      // console.log(res)
                      this.getPointOrder(this.curType)
                      this.closePayPop()
                    },
                    fail: (failmsg) => {
                      // console.log(failmsg)
                    }
                  })
                } else if (this.submitData.type == 26 && res.data.is_mini_vsp) {
                  this.Jump('/buyTonglianWait',{ order_id, pay_type: 3 })
                } else if (this.submitData.type == 34 && res.data.jsApiParameters) {
                  if (small.wxCache('adapayPlugVersion') == 'jump_adapay_mini') {
                    const jsApiParameters = typeof res.data.jsApiParameters === 'object' ? res.data.jsApiParameters : JSON.parse(res.data.jsApiParameters) 
                    this.hfAppId = jsApiParameters.wx_app_id
                    const that = this
                    wx.navigateToMiniProgram({
                      appId: jsApiParameters.wx_app_id,
                      path: jsApiParameters.miniapp_path,
                      success(res) {
                        // 打开成功
                        // console.log(res)
                      },
                      fail(error) {
                        // that.$Error('跳转失败')
                        that.Jump('pointOrder')
                      }
                    })
                  } else if (small.wxCache('adapayPlugVersion') == 'self') {
                    const payData = JSON.parse(res.data.jsApiParameters)
                    wx.requestPayment({
                      timeStamp: payData.timeStamp,
                      nonceStr: payData.nonceStr, //
                      package: payData.package, //
                      signType: payData.signType, //微信签名方式
                      paySign: payData.paySign, //微信签名
                      success: (res) => {
                        // console.log(res)
                        this.getPointOrder(this.curType)
                        this.closePayPop()
                      },
                      fail: (failmsg) => {
                        // console.log(failmsg)
                      }
                    })
                  } else {
                    const adapayPlugin = small.wxCache('adapayPlugVersion') == 'new' ? requirePlugin("Adapay") : requirePlugin("adapay-plugin")              
                    // 汇付分账
                    this.isSubmit = false
                    // console.log('typeof obj',  typeof res.data.jsApiParameters === 'object')
                    const hfPay= res.data.jsApiParameters
                    if (hfPay) {
                      adapayPlugin.requestPay(hfPay, this.paySuccess, this.payError);
                    }
                  }
                } else{
                  setTimeout(() => {
                    this.init()
                  }, 1000)
                  this.closePayPop()
                }
              } else {
                this.$Error(res.msg)
              }
            })
          }
        }
      },
      JumpName(url, data) {
        this.$JumpName(this, url, data)
      },
      // 输入支付密码点击确定
      payPwdCallback() {
        const submitData = this.submitData
        // var payType = $('input[name="type"]:checked').val()
        const payType = submitData.type
        const order_id = submitData.order_id
        const money_type = submitData.moneyType
        // var money_type = $('input[name="money_type"]:checked').val()
        // var popup_show = $('#popup_show').val()
        // const balance = this.payPopData.balance
        // var sumPrice = $('.balance_money').text()
        // const must_pay_password = this.must_pay_password
        // var must_pay_password = $(':hidden[name="must_pay_password"]').val()
        const global_alipay_currency = submitData.global_alipay_currency
        // var global_alipay_currency = $('[name=global_alipay_currency]').val()
        // // console.log(must_pay_password);
        const hantepay = submitData.hantepay
        const params = { hantepay: hantepay, global_alipay_currency: global_alipay_currency, pay_type: payType, order_id: order_id, money_type: money_type }
        if (payType == 34) {
          params.adapay_pay_type = submitData.adapay_pay_type
        }
        this.$loadingWrap.show()
        setTimeout(() => {
          this.$loadingWrap.close()
        }, 10000)
        pointPayUrl(params).then(res => {
          this.$loadingWrap.close()
          if (res.status == 1) {
            // window.location.href = res.url
            // TODO 小程序支付
            if(this.submitData.type == 2 && res.data.jsApiParameters){
              const payData = JSON.parse(res.data.jsApiParameters)
              wx.requestPayment({
                timeStamp: payData.timeStamp,
                nonceStr: payData.nonceStr, //
                package: payData.package, //
                signType: payData.signType, //微信签名方式
                paySign: payData.paySign, //微信签名
                success: (res) => {
                  // console.log(res)
                  this.getPointOrder(this.curType)
                  this.closePayPop()
                },
                fail: (failmsg) => {
                  // console.log(failmsg)
                }
              })
            } else if (this.submitData.type == 26 && res.data.is_mini_vsp) {
              this.Jump('/buyTonglianWait',{ order_id, pay_type: 3 })
            } else if (this.submitData.type == 34 && res.data.jsApiParameters) {
              if (small.wxCache('adapayPlugVersion') == 'jump_adapay_mini') {
                const jsApiParameters = typeof res.data.jsApiParameters === 'object' ? res.data.jsApiParameters : JSON.parse(res.data.jsApiParameters) 
                this.hfAppId = jsApiParameters.wx_app_id
                const that = this
                wx.navigateToMiniProgram({
                  appId: jsApiParameters.wx_app_id,
                  path: jsApiParameters.miniapp_path,
                  success(res) {
                    // 打开成功
                    // console.log(res)
                  },
                  fail(error) {
                    // that.$Error('跳转失败')
                    that.Jump('pointOrder')
                  }
                })
              } else if (small.wxCache('adapayPlugVersion') == 'self') {
                  const payData = JSON.parse(res.data.jsApiParameters)
                  wx.requestPayment({
                    timeStamp: payData.timeStamp,
                    nonceStr: payData.nonceStr, //
                    package: payData.package, //
                    signType: payData.signType, //微信签名方式
                    paySign: payData.paySign, //微信签名
                    success: (res) => {
                      // console.log(res)
                      this.getPointOrder(this.curType)
                      this.closePayPop()
                    },
                    fail: (failmsg) => {
                      // console.log(failmsg)
                    }
                  })
                } else {
                const adapayPlugin = small.wxCache('adapayPlugVersion') == 'new' ? requirePlugin("Adapay") : requirePlugin("adapay-plugin")              
                // 汇付分账
                this.isSubmit = false
                // console.log('typeof obj',  typeof res.data.jsApiParameters === 'object')
                const hfPay= res.data.jsApiParameters
                if (hfPay) {
                  adapayPlugin.requestPay(hfPay, this.paySuccess, this.payError);
                }
              }
            } else{
              setTimeout(() => {
                this.init()
              }, 1000)
              this.closePayPop()
            }
          } else {
            this.$Error(res.msg)
          }
        })
      },
      // 关闭输入支付密码弹窗
      closePwd() {
        this.showPwd = false
      }
    },
    created() {
      if (small.wxCache('adapayPlugVersion') == 'jump_adapay_mini') {
        this.remark = 1
      }
      this.init()
    },
    mounted() {
      if (small.wxCache('adapayPlugVersion') == 'jump_adapay_mini') {
        window.addEventListener('wxshow', () => {
          let options = wx.getEnterOptionsSync();
          // wx1e18d140f890f2c5，wx308088053f4ecc3a
          if (options.scene == '1038' && options.referrerInfo.appId == this.hfAppId && this.remark == 2) {
            // 代表从收银台小程序返回
            this.Jump('pointOrder')
          }
        }),
        window.addEventListener('wxHide', () => {
          this.remark = 2
        })
      }
    },
  })
</script>

<style lang="scss">
@import "src/styles/variables.scss";
@import "src/styles/mixin";
@import "src/styles/order/detail";
.point-detail-container{
  .total-price{
    .price{
      font-size:32px;
      color: #F42B2B;
    }
  }
  .actions{
    padding-bottom:100px;
  }
  .bottom-btn{
    position:fixed;
    left:0;
    bottom:0;
    width:100%;
    // height:98px;
    padding:14px 16px;
    font-size:0;
    background:#fff;
    text-align:right;
    .inline-block{
      display:inline-block;
    }
    .btn{
      width:100%;
      height:72px;
      // margin:0 6px;
      font-size:28px;    
      color:#fff;
      background:linear-gradient(-90deg,rgba(233,1,4,1),rgba(254,27,73,1));
      &.no-border{
        border:0;
      }
      &.return-btn {
        margin-top: 10px;
      }
    }
  }
}
.refund-btn-top {
  margin: 20px 0;
}
</style>